package com.zhoufy.service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * Created with IntelliJ IDEA by ChouFy on 2020-04-14.
 *
 * @author zhoufy
 */
public class UserServiceImpl implements UserService {


    @Override
    public String sayHello(String name) {
        return "say hello--" + name;
    }


    @Override
    public RpcRequest isOk(RpcRequest request) {

        if(request == null){ return  new RpcRequest();}

        if(!request.getClassName().startsWith("UserService")){
            return new RpcRequest();
        }
        request.setRequestId("ok");
        return request;
    }

    public static void startServer(String hostName, int port) throws InterruptedException {
        NioEventLoopGroup boosGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(boosGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new UserServiceHandle());


                    }
                });


        ChannelFuture bind = serverBootstrap.bind(hostName, port);
        bind.sync();




    }
}
